// Package controllers
// @program: BannerStudioBlog.background
// @author: Hyy
// @create: 2022-02-12 00:15
package controllers

import (
	"bannerstudioblog/models"
	"bannerstudioblog/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type TenCloudCosController struct {
	beego.Controller
}

// Upload
// @Title Upload
// @Description 上传文件到腾讯云
// @Param	files	formData	true	"想要上传的文件"
// @router /upload [post]
func (t *TenCloudCosController) Upload() {
	files, err := t.GetFiles("files")
	var result string
	if err != nil {
		logs.Warn(err)
		t.Data["json"] = models.GetRevaErr(err, "上传失败")
		t.ServeJSON()
		return
	}
	for _, file := range files {
		imgType := file.Header["Content-Type"][0]
		if imgType != "image/png" && imgType != "image/jpg" && imgType != "image/jpeg" && imgType != "image/gif" {
			logs.Warn("上传图片非jpg,png,jpeg,gif,请重新上传！")
			t.Data["json"] = models.GetRevaErr(nil, "上传图片非jpg,png,jpeg,gif,请重新上传！")
			t.ServeJSON()
			return
		} else if file.Size/1024 > 2000 {
			logs.Warn("上传图片大于2M，请重新上传")
			t.Data["json"] = models.GetRevaErr(nil, "上传图片大于2M,请重新上传！")
			t.ServeJSON()
			return
		} else {
			// *multipart.FileHeader
			f, err := file.Open()
			if err != nil {
				logs.Warn("ERROR:", err)
				return
			}
			defer f.Close()
			result = utils.Upload(file.Filename, f)
			if result == "" {
				t.Data["json"] = models.GetRevaOk("上传失败！")
				t.ServeJSON()
				return
			}
		}
	}
	t.Data["json"] = models.GetRevaOkAndDes("上传成功！", result)
	t.ServeJSON()
}

// DeleteFile
// @Title DeleteFile
// @Description 从腾讯云删除文件
// @Param	fileName	path	string   true	"想要删除的文件名称"
// @router /deleteFile/:fileName [delete]
func (t *TenCloudCosController) DeleteFile() {
	fileName := t.GetString(":fileName")
	if fileName != "" {
		result := utils.Delete(fileName)
		if result {
			t.Data["json"] = models.GetRevaOk("删除成功！")
			t.ServeJSON()
			return
		} else {
			t.Data["json"] = models.GetRevaOk("删除失败！")
			t.ServeJSON()
			return
		}
	} else {
		t.Data["json"] = models.GetRevaOk("删除失败,文件名不可以为空！")
		t.ServeJSON()
		return
	}
}

//// Download
//// @Title Download
//// @Description 从腾讯云下载图片
//// @Param	fileName	path	string   true	"想要下载的文件名称"
//// @Param	fileSavePath	path	string   true	"想要保存的路径"
//// @router /download/:fileName/:fileSavePath [post]
//func (t *TenCloudCosController) Download() {
//	fileName:=t.GetString("fileName")
//	fileSavePath:=t.GetString("fileSavePath")
//	if fileName!=""&&fileSavePath!="" {
//		utils.DownLoad(fileName,fileSavePath)
//		t.Data["json"]=models.GetRevaOk("下载成功！")
//		t.ServeJSON()
//		return
//	}else {
//		t.Data["json"]=models.GetRevaErr(nil,"下载失败，文件名/保存路径不可为空！")
//		t.ServeJSON()
//		return
//	}
//}
